from flask import Blueprint, request
import _thread as thread
import base64
import hashlib
import hmac
import json
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
from threading import Lock
import websocket
from PIL import Image
from socketIO import socketIO as socketio

from controller.LoginController import getNowUserInfo

from entity.ChatHistory import ChatHistory
from entity.Log import Log

from db import db

talkController = Blueprint('talkController',__name__)

question = ''
SocketThread = None
thread_lock = Lock()
answer = ''

@socketio.on('connect', namespace='/chat')
def chat_connect():
    print('namespace=chat连接成功')
    pass

@socketio.on('start_chat',namespace='/chat')
def start_chat(data):
    global question
    question = data.get('question')
    username = data.get('username')
    # 加入聊天历史 同时创建日志
    chatHistory = ChatHistory(username, question)
    db.session.add(chatHistory)
    db.session.commit()

    log = Log(username, '智能问答')
    db.session.add(log)
    db.session.commit()

    global SocketThread
    with thread_lock:
        if SocketThread is None:
            SocketThread = socketio.start_background_task(target=background_thread)

# 正常聊天 断开连接触发
@socketio.on('disconnect', namespace='/chat')
def disconnect_msg():
    print('正常对话连接断开!')

# 建立连接后的会运行的线程
def background_thread():
    try:
        cfg = config()
        appid = cfg["appid"]
        api_secret = cfg["api_secret"]
        api_key = cfg["api_key"]


        text = []
        text.clear()

        global question
        Spark_url = cfg["Spark_url"]
        domain = cfg["domain"]
        question = getText(question)
        startChat(appid, api_key, api_secret, Spark_url, domain, question)
    except Exception as e:
        print(e)

# websocket 后端与讯飞之间建立连接 需要鉴权
class Ws_Param(object):
    # 初始化
    def __init__(self, APPID, APIKey, APISecret, Spark_url):
        self.APPID = APPID
        self.APIKey = APIKey
        self.APISecret = APISecret
        self.host = urlparse(Spark_url).netloc
        self.path = urlparse(Spark_url).path
        self.Spark_url = Spark_url

    # 生成url
    def create_url(self):
        # 生成RFC1123格式的时间戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字符串
        signature_origin = "host: " + self.host + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + self.path + " HTTP/1.1"

        # 进行hmac-sha256进行加密
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()

        signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'

        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')

        # 将请求的鉴权参数组合为字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": self.host
        }
        # 拼接鉴权参数，生成url
        url = self.Spark_url + '?' + urlencode(v)
        # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释，比对相同参数时生成的url与自己代码生成的url是否一致
        return url

# 收到websocket错误的处理
def on_error(ws, error):
    print("webSocket error:", error)

# 收到websocket关闭的处理
def on_close(ws, one, two):
    print("webSocket closed")

# 收到websocket连接建立的处理
def on_open(ws):
    thread.start_new_thread(run, (ws,))

# 收到websocket消息的处理
def on_message(ws, message):
    data = json.loads(message)
    code = data['header']['code']
    if code != 0:
        print(f'请求错误: {code}, {data}')
        ws.close()
    else:
        choices = data["payload"]["choices"]
        status = choices["status"]
        content = choices["text"][0]["content"]
        print(content, end="")
        socketio.emit('server_response',{"data": content},namespace='/chat')
        global answer
        answer += content
        if status == 2:
            global SocketThread
            socketio.emit('server_response', {"data": "[over]"}, namespace='/chat')
            SocketThread = None
            ws.close()

def run(ws, *args):
    data = json.dumps(gen_params(appid=ws.appid, domain=ws.domain, question=ws.question))
    ws.send(data)

def startChat(appid, api_key, api_secret, Spark_url, domain, question):
    wsParam = Ws_Param(appid, api_key, api_secret, Spark_url)
    websocket.enableTrace(False)
    wsUrl = wsParam.create_url()
    ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
    ws.appid = appid
    ws.question = question
    ws.domain = domain
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

# 生成调用api所需的参数 按照api要求的来
def gen_params(appid, domain, question):
    """
    通过appid和用户的提问来生成请参数
    """
    data = {
        "header": {
            "app_id": appid,
            "uid": "721"
        },
        "parameter": {
            "chat": {
                "domain": domain,
                "temperature": 0.5,
                "max_tokens": 2048
            }
        },
        "payload": {
            "message": {
                "text": question
            }
        }
    }
    return data

# config配置类
def config():
    config = {}
    config["appid"] = "3c591f62"
    config["api_secret"] = "Y2M2YWU0N2QzOGE0ODcyMmY3ODgzMWY2"
    config["api_key"] = "14a25fc24a288e7c358a0e795275aa57"
    config["domain"] = "generalv3.5"
    config["Spark_url"] = "wss://spark-api.xf-yun.com/v3.5/chat"
    return config

def getlength(text):
    length = 0
    for content in text:
        temp = content["content"]
        leng = len(temp)
        length += leng
    return length

def getText(content):
    text = []
    jsoncon = {}
    jsoncon["role"] = "user"
    jsoncon["content"] = content
    text.append(jsoncon)
    return text